<template>
  <div class="group-send-log">
    <el-table :data="groupSendLog" stripe class="group-send-log-table" height="100%">
      <!-- <el-table-column label="任务类型" :filters="taskTypes" prop="tasktype" :filter-method="filterTaskTypes"> -->
      <el-table-column label="任务类型" prop="tasktype" width="120">
        <template slot-scope="scope">
          <span v-text="tasktypeMap[scope.row.tasktype]"></span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" width="80">
        <template slot-scope="scope">
          <span v-text="restypeMap[scope.row.restype]"></span>
        </template>
      </el-table-column>
      <el-table-column label="微信昵称">
        <template slot-scope="scope">
          <span v-text="wechatsNameMap[scope.row.wechatId] || scope.row.wechatId"></span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" prop="state" :formatter="taskStateFormatter"></el-table-column>
      <el-table-column label="备注" prop="remarks"></el-table-column>
      <el-table-column label="预计执行时间" prop="execute_time"></el-table-column>
      <el-table-column label="实际执行时间" prop="update_time">
        <template slot-scope="scope">
          <span
            v-if="scope.row.update_time"
            v-text="$options.filters.transformTime2Minute(scope.row.update_time)"
          ></span>
          <span v-else v-text="'待执行'"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <!--  -1暂停     1开启中     0已完成    2取消 -->
        <template slot-scope="{ row }">
          <el-button v-if="row.state === 1" type="text" size="small" @click="modifyState(row, -1)">暂停</el-button>
          <el-button v-if="row.state === -1" type="text" size="small" @click="modifyState(row, 1)">继续</el-button>
          <el-button v-if="row.state === 1 || row.state === -1" type="text" size="small" @click="modifyState(row, 2)">
            取消
          </el-button>
          <el-button type="text" size="small" @click="getAutoTaskDetail(row)">详情</el-button>
          <el-button type="text" size="small" @click="deleteTask(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin: 5px"
      :current-page="currentPage"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="7"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 刷新日志 -->
    <el-button style="position: absolute; bottom: 5px; right: 20px" size="small" @click="queryLogData">
      刷新日志
    </el-button>

    <!-- 任务详情 -->
    <el-dialog append-to-body class="task-detail" title="任务详情" :visible.sync="taskDetailVisiable">
      <div
        style="width: 50%"
        :class="[
          {
            'chat-link': rowDetail.restype === 6
          },
          {
            'chat-app': rowDetail.restype === 13
          }
        ]"
        v-html="decodeChat(rowDetail)"
      ></div>

      <ul class="detail-ls">
        <li>
          <p style="width: 120px" v-text="'任务总数'"></p>
          <p v-text="taskDetail.task_allSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'执行中的任务数'"></p>
          <p v-text="taskDetail.task_startSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'暂停的任务数'"></p>
          <p v-text="taskDetail.task_stopSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'取消的任务数'"></p>
          <p v-text="taskDetail.task_cancelSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'失败的任务数'"></p>
          <p v-text="taskDetail.task_failSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'结束的任务数'"></p>
          <p v-text="taskDetail.task_endSize"></p>
        </li>
        <li>
          <p style="width: 120px" v-text="'成功的任务数'"></p>
          <p v-text="taskDetail.task_successSize"></p>
        </li>
      </ul>
      <span slot="footer">
        <el-button size="medium" @click="taskDetailVisiable = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getTaskInfoList, getTaskDetail, updateTaskState, taskDelete } from '@/api/httpApi'
const imgError = require('@/assets/svg/conversation-image-error.svg')

export default {
  name: 'GroupAssistantLog',
  props: {
    currentTab: {
      type: [Number, String],
      default: 1
    }
  },
  data() {
    return {
      groupSendLog: [], // 群发日志
      tasktypeMap: {
        1: 'PC群发消息',
        2: 'PC发朋友圈',
        3: '删除好友',
        4: '删除群聊',
        5: '群发群消息',
        6: '按标签群发',
        7: '发朋友圈',
        8: '批量加好友'
      }, // 任务类型
      restypeMap: {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13,
        1: '文本',
        2: '图片',
        3: '语音',
        4: '视频',
        6: '链接',
        13: '小程序'
      }, // 消息类型
      pageSize: 20,
      currentPage: 1,
      totalNum: 0,
      taskDetail: {}, // 任务详情
      rowDetail: {}, // 任务详情
      taskDetailVisiable: false // 任务详情可见
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      wechatsNameMap: 'conversation/wechatsNameMap',
      currentWeChatId: 'conversation/currentWeChatId'
    })
  },
  watch: {
    // wechat改变 重新拉取日志
    currentWeChatId(wxid) {
      if (wxid) {
        // 线上的日志
        this.queryLogData()
      } else {
        this.groupSendLog = []
      }
    },
    currentTab() {
      this.queryLogData()
    }
  },
  created() {
    // 查询日志
    if (this.currentWeChatId) {
      this.queryLogData()
    }
  },
  methods: {
    // 查询日志
    queryLogData() {
      getTaskInfoList(
        this.currentUser.SupplierId,
        this.currentUser.UnionId,
        this.currentPage,
        this.pageSize,
        this.currentTab,
        ''
      ).then((res) => {
        if (res.code === 0) {
          this.groupSendLog = res.data.list || []
          this.totalNum = res.data.total || 0
        }
      })
    },
    // 查询任务详情
    getAutoTaskDetail(row) {
      this.rowDetail = row
      this.taskDetail = {}
      getTaskDetail(row.id).then((res) => {
        if (res.code === 0 && res.data) {
          this.taskDetail = res.data
          this.taskDetailVisiable = true
        }
      })
    },
    // 删除任务
    deleteTask(row) {
      taskDelete(row.id).then((res) => {
        if (res.code === 0) {
          this.groupSendLog = this.groupSendLog.filter((x) => {
            return x.id !== row.id
          })
        }
      })
    },
    // 修改任务状态
    modifyState(row, state) {
      updateTaskState(row.id, state).then((res) => {
        if (res.code === 0) {
          for (const gsl of this.groupSendLog) {
            if (gsl.id === row.id) {
              gsl.state = state
              break
            }
          }
          // this.$message.success('修改任务状态成功！')
        }
      })
    },
    // // 任务类型过滤器
    // filterTaskTypes(value, row, column) {
    //   const property = column['property']
    //   return row[property] === value
    // },
    // 任务状态格式化
    taskStateFormatter(row) {
      const stateMap = {
        '-1': '暂停',
        0: '已完成',
        1: '开启中',
        2: '取消'
      }
      return stateMap[row.state]
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryLogData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryLogData()
    },
    // 解析内容
    decodeChat(chat) {
      const content = chat.content
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let thumb = ''
      let str = ''

      switch (chat.restype) {
        // 文本 1
        case 'Text':
        case 1:
          // return phiz.qqFaceImgMap(content)
          return content
        // 图片 2
        case 'Picture':
        case 2:
          return `<img class="chat-img" src="${content}"  alt="图片"/>`
        // 语音 3
        case 'Voice':
        case 3:
          if (content.endsWith('.amr')) {
            thumb = content.replace(/.amr$/, '.mp3')
          } else {
            thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
          }
          return ` <audio src="${thumb}" alt="语音" controls></audio>`
        // 视频 4
        case 'Video':
        case 4:
          return `<video class="video-box" src="${content}" type="video/mp4" alt="视频" controls></video>`
        // 链接消息 6
        case 'Link':
        case 6:
          str = `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                          <span class="link-des">${jContent.Des}</span>
                          <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
          return str

        // 小程序 13
        case 'WeApp':
        case 13: {
          let appIcon = imgError
          let appSource = '无效小程序'
          let appTitle = '无效小程序'
          let appThumb = ''
          let appTypeStr = '小程序'
          if (typeof content === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
            appSource = jContent.Source
            appTitle = jContent.Title || jContent.Des
            appThumb = jContent.Thumb
            appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
          }

          str = `
                  <div class="app-des">
                  <img class="app-icon" src="${appIcon}" alt="icon" />
                  <span class="app-source ellipsis">${appSource}</span>
                  </div>
                  <div class="app-title ellipsis">${appTitle}</div>
                  <img class="app-img" src="${appThumb}" />
                  <div class="app-typestr">${appTypeStr}</div>
                   `
          return str
          // return jContent
        }

        // 不支持的消息
        default:
          return `不支持的消息类型${chat.ContentType}`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.group-send-log {
  height: 100%;
  width: 100%;
  padding: 0 20px;
  overflow: hidden;
  display: flex;
  align-items: center;
  flex-direction: column;
  ::v-deep .group-send-log-table {
    width: 100%;
    height: 100%;
    .el-table__header-wrapper {
      min-height: 40px;
      display: flex;
      align-items: center;
      background-color: #ff9f000d;
      .el-table__header {
        th {
          background-color: #ff9f000d;
          padding: 0;
          border-bottom: none;
        }
      }
    }
  }
}
</style>
